layui.use(['form', 'table'], function () {
    const form = layui.form,
        $ = layui.jquery;

    // 初始化
    $(function () {
        setTimeout(function () {
            const categoryCode = $("#code").val();
            if (categoryCode === undefined || categoryCode === "") {
                layer.msg("页面出错，请返回并重新加载");
                return;
            }
            // 获取分类详情
            $.get(URL_SYSTEM_CATEGORY + "/" + categoryCode, function (res) {
                if (res.code === 0) {
                    form.val('category-val-filter', res.data);
                }
            });
        }, 50);
    });

    // 取消按钮
    $("#btn-category-cancel").click(function () {
        const index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

    form.on('submit(category-submit)', function (data) {
        let url, method;
        if (isEmpty(data.field.code)) {
            url = URL_SYSTEM_CATEGORY;
            method = 'post';
        } else {
            url = URL_SYSTEM_CATEGORY + '/' + data.field.code;
            method = 'put';
        }
        $.ajax({
            type: method,
            url: url,
            data: JSON.stringify({
                ...data.field
            }),
            headers: COMMON_HEADERS,
            success: function (res) {
                if (res.code === 0) {
                    const index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.layer.msg(OPERATION_SUCCESS.MESSAGE, {
                        time: 2000
                    });
                    parent.layui.table.reload(TABLE_ID_CATEGORY);
                } else {
                    layer.alert(JSON.stringify(res), OPERATION_SUCCESS.ICON_CONTENT);
                }
            },
            error: function (res) {
                layer.alert(JSON.stringify(res), OPERATION_SUCCESS.ICON_CONTENT);
            }
        });
        // 防止表单的重复提交
        return false;
    });
})
